package com.weipu.common.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

import com.weipu.common.DXApplication;


/**
 * 
 * 通用工具类。
 * @version [版本号, 2012-9-17]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 * 
 * @author hjd008
 */
public class Common
{
    /**
     * 获取版本号。
     * 
     * @param cls
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getVersionName()
    {
        
        try
        {
            Context context = DXApplication.getContext();
            
            PackageInfo pinfo =
                context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            return pinfo.versionName;
        }
        catch (Exception e)
        {
            return "1.0";
        }
    }
    
    /**
	 * 获取当前应用程序的版本号。
	 */
	public static int getAppVersion(Context context) {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 1;
	}
    
    public static String getStackTrace(Throwable t)
    {
	    StringWriter sw = new StringWriter();
	    PrintWriter pw = new PrintWriter(sw, true);
	    t.printStackTrace(pw);
	    pw.flush();
	    sw.flush();
	    return sw.toString();
    }
    
	/**
	 * 使用MD5算法对传入的key进行加密并返回。
	 */
	public static String hashKeyForDisk(String key) {
		String cacheKey;
		try {
			final MessageDigest mDigest = MessageDigest.getInstance("MD5");
			mDigest.update(key.getBytes());
			cacheKey = bytesToHexString(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			cacheKey = String.valueOf(key.hashCode());
		}
		return cacheKey;
	}

	private static String bytesToHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}

}
